function [out ] = cross_valid(X,Y,NCV,flow_function,varargin)

    %  Constants
    NTrial = size(X,3);
    NTrialTest = fix(NTrial/NCV);
    out = zeros(size(X,3),1);
    
    %cross validation
    for iCV = 1:NCV 

        % calculate the positions of the testing dataset
        idxTest = 1+(iCV-1)*NTrialTest:iCV*NTrialTest;
        if iCV ==NCV
            idxTest = 1+(iCV-1)*NTrialTest:NTrial;
        end
        
        % set the the rest as training dataset
        idxTraining = 1:NTrial;
        idxTraining(idxTest)=[]; 

        if isempty(varargin)
            %example: mdm_freq(COVtest,COVtrain,Ytrain,varargin)
            Ytest = flow_function(X(:,:,idxTest,:),X(:,:,idxTraining,:),Y(idxTraining));
        else
            Ytest = flow_function(X(:,:,idxTest,:),X(:,:,idxTraining,:),Y(idxTraining),varargin{:});
        end
        out(idxTest) = Ytest;

    end